<?php

namespace app\appletsapi\controller;

use app\appletsapi\validate\Place as PlaceValidate;
use app\common\model\Aftersales;
use app\common\model\OfflineRecord;
use app\common\model\Order as OrderModel;
use app\common\model\Cart;
use app\common\model\OrderDetail;
use app\common\model\Shops;
use app\common\model\ShopsSeat;
use plug\SHttp;

class Order extends Base
{
    /**
     * @route('applets/GetOrderList','get')
     * 普通商品和兑换商品订单列表
     */
    public function GetOrderList()
    {
        $OrderModel = new OrderModel();
        $limit = input('get.limit') ? input('get.limit') : 6;
        $status = input('get.status') ? input('get.status') : '';
        $pname = input('get.product_name') ? input('get.product_name') : '';
        $iscomment = input('get.is_comment') ? input('get.is_comment') : '';
        $class_ids = [1, 2];
        $data = $OrderModel->shops_order_list([
            'user_id' => $this->_userid,
            'order_status' => $status,
            'product_name' => $pname,
            'class_ids' => $class_ids,
            'is_comment' => $iscomment], 'o.order_id desc', $limit, false, [
            'o.order_id', 'o.shop_id', 's.shop_name', 'o.pay_amount', 'o.order_status', 'o.pay_status', 'o.express_fee', 's.imagesurl', 'o.order_type', 'points'
        ], [
            'detail_id', 'order_id', 'product_id', 'product_name', 'p_s_name', 'cover_url', 'sale_price', 'amount', 'cover_url', 'quantity', 'growth_coin', 'growth_coin_amount'
        ]);
        $data = [
            'data' => $data['data'],
            "total" => $data['page']['total'],
            "per_page" => $data['page']['per_page'],
            "current_page" => $data['page']['current_page'],
            "last_page" => $data['page']['last_page'],
        ];
        $this->result($data, 1, '操作成功');
    }

    /**
     * @route('applets/GetOrderDetail','get')
     * 获取普通商品和兑换商品订单详情
     */
    public function GetOrderDetail()
    {
        $order_id = input('get.order_id');
        $user = $this->GetUserInfo();
        $data = [];
        $orderModel = new OrderModel();
        $where = [
            ['user_id', '=', $user['user_id']],
            ['order_id', '=', $order_id],
            ['order_type', 'in', [1, 2]],
            ['is_del', '=', 1]
        ];
        $order = $orderModel->getOne($where);
        if (empty($order)) {
            $this->result('', -1, '用户不存在的订单');
        }
        $data['order'] = $order->toArray();
        $data['order']['total'] = 0;
        $item = 'od.*,s.shop_id';
        $detail = $orderModel->api_order_details($order_id, $item);
//        var_dump($detail);die;
        if (empty($order)) {
            $this->result('', -1, '不存在的订单详情');
        }
        $shop_ids = array_column($detail, 'shop_id');
        $shopModel = new Shops();
//        var_dump($shop_ids);die;
        $shops = $shopModel->get_list(['shop_ids' => $shop_ids], '', 'shop_id,shop_name,shop_phone,address,province,city,area,imagesurl')->toArray();
        $shops = array_column($shops, null, 'shop_id');
//        var_dump($shops);die;
        foreach ($detail as $value) {
            $data['order']['total'] += $value['quantity'];
            $detailinfo[$value['shop_id']]['shopinfo'] = $shops[$value['shop_id']];
            $detailinfo[$value['shop_id']]['detailinfo'][] = $value;
        }
        $data['productinfo'] = array_values($detailinfo);
        $this->result($data, 1, '返回信息');
    }

    /**
     * @route('applets/GetSeatOrderDetail','post')
     * 通过桌号获取订单详情
     */
    public function GetSeatOrderDetail()
    {
        $seatModel = new ShopsSeat();
        $seatinfo = $seatModel->getOne([['seat_id', '=', $this->_seatid], ['shop_id', '=', $this->_shopid]]);
        if (empty($seatinfo)) {
            $this->result('', -1, '该商铺不存在的座位号');
        }
//        var_dump(234);die;
        $data = [];
        $orderModel = new OrderModel();
        $order = $orderModel->checkOfflineOrderExist($seatinfo);
        if (empty($order)) {
//            这个返回类型不能改
            $this->result(NULL, 1, '该桌暂无下单记录');
        }
        $data['order'] = $order;
        $data['order']['total'] = 0;
        $item = 'od.*,s.shop_id';
        $detail = $orderModel->api_order_details($order['order_id'], $item);
//        var_dump($detail);die;
        if (empty($detail)) {
            $this->result('', -1, '不存在的订单详情');
        }
        $shop_ids = array_column($detail, 'shop_id');
        $shopModel = new Shops();
//        var_dump($shop_ids);die;
        $shops = $shopModel->get_list(['shop_ids' => $shop_ids], '', 'shop_id,shop_name,shop_phone,address,province,city,area,imagesurl')->toArray();
        $shops = array_column($shops, null, 'shop_id');
//        var_dump($shops);die;
        foreach ($detail as $value) {
            $data['order']['total'] += $value['quantity'];
            $detailinfo[$value['shop_id']]['shopinfo'] = $shops[$value['shop_id']];
            $detailinfo[$value['shop_id']]['detailinfo'][] = $value;
        }
        $data['productinfo'] = array_values($detailinfo);
        $this->result($data, 1, '返回信息');
    }

//    /**
//     * @route('applets/GetOfflineOrderList','get')
//     * 获取线下订单列表
//     */
    public function GetOfflineOrderList()
    {
        $orderModel = new OrderModel();
        if(input('get.status',1) == 1){
            $status = [2,3,4];
        } else {
            $status = [6,7];
        }
        $where = [
            'shop_id' => $this->_shopid,
            'user_id' => $this->_userid,
            'order_type' => [5],
            'order_status' => $status,
        ];
        $data = $orderModel->GetOfflineOrderList($where, '*', 'order_id desc', $this->limit);
        $this->result($data, 1, '返回信息');
    }

//    /**
//     * @route('applets/GetOfflineOrderDetail','get')
//     * 获取线下订单详情
//     */
    public function GetOfflineOrderDetail()
    {
        $order_id = input('get.order_id');
        $orderModel = new OrderModel();
        $where = [
            'order_id' => $order_id,
            'order_type' => [5],
        ];
        $data = $orderModel->GetOfflineOrderInfo($where, '*', $this->limit);
        $this->result($data, 1, '返回信息');
    }

//    /**
//     * @route('applets/Settlement','post')
//     * 线下购物车结算
//     */
    public function Settlement()
    {
        $ids = input('post.cart_ids');
        $CartModel = new Cart();
        $user = $this->GetUserInfo();
        $data = $CartModel->Settlement($user, $ids, 0, 2);
        if (!$data) {
            $this->result([], -1, $CartModel->getError());
//			$this->result([],-1,'商铺或者商品已下架');
        }
        $this->result($data, 1, '操作成功');
    }

//    /**
//     * @route('applets/UserCancel')
//     * 用户撤销订单
//     */
    public function UserCancel()
    {
        $orderModel = new OrderModel();
        $where = [
            'order_id' => input('post.order_id'),
            'user_id' => $this->_userid,
        ];
        $rs = $orderModel->operatecancel($where);
        if ($rs === false) {
            $this->result('', -1, $orderModel->getError());
        }
        $this->result('', 1, '操作成功');
    }

//    /**
//     * @route('applets/UserCancelOperation')
//     * 用户取消撤销订单操作
//     */
    public function UserCancelOperation()
    {
        $orderModel = new OrderModel();
        $where = [
            'order_id' => input('post.order_id'),
            'user_id' => $this->_userid,
        ];
        $rs = $orderModel->operatecanceloperation($where);
        if ($rs === false) {
            $this->result('', -1, $orderModel->getError());
        }
        $this->result('', 1, '操作成功');
    }

//    /**
//     * @route('applets/UserEditOrder')
//     * 用户修改订单
//     */
    public function UserEditOrder()
    {
        $param = input('post.');
        $validate = new PlaceValidate();
        $res = $validate->scene('edit')->check($param);
        if(!$res){
            $this->result('',-1,$validate->getError());
        }
        $orderModel = new OrderModel();
        $where = [
            'order_id' => $param['order_id'],
            'user_id' => $this->_userid,
        ];
        unset($param['order_id']);
        $rs = $orderModel->usereditorder($where,$param);
        if ($rs === false) {
            $this->result('', -1, $orderModel->getError());
        }
        $this->result('', 1, '操作成功');
    }

    /**
     * @route('applets/autoUpdateStatus')
     * 自动更新订单为已完成状态
     */
    public function autoUpdateStatus()
    {
        $orderModel = new OrderModel();
        $where = [
            ['order_status','=',3],
            ['receive_time','<',time()],
        ];
        $rs = $orderModel->allowField(true)->save(['order_status'=>4], $where);
        if ($rs === false) {
            $this->result('', -1, $orderModel->getError());
        }
        $this->result('', 1, '操作成功');
    }

    /**
     * @route('applets/device')
     */
    public function device()
    {

        $orderModel = new \app\common\model\Order();

        $rs = $orderModel->DeviceOrderInfo(872);


    }

    /**
     * @route('applets/prints','get')
     */
    public function prints(){


        $offineModel = new OfflineRecord();
        $SeatModel = new ShopsSeat();
        $orderModel = new \app\common\model\Order();
        $detailModel = new OrderDetail();

        $data = [];

        $orderId = input('order_id');
        $detailId = input('detail_id');

        $order = $orderModel->getOne(['order_id' => $orderId],'order_id,shop_id,order_time,pay_amount,orderno,remarks');

        $seatId = $offineModel->getOne(['order_id' => $orderId],'seat_id')['seat_id'];
        $data['table'] = $SeatModel->getOne(['seat_id' => $seatId],'seat_num')['seat_num'];
        $data['orderno'] = $order['orderno'];
        $data['order_time'] = $order['order_time'];
        $data['remarks'] = $order['remarks'];

        if($detailId == 0){
            // 总单
            $data['detail'] = $orderModel->shops_order_details($orderId,'od.detail_id,od.order_id,od.product_name,od.quantity,');
        }else{
            // 分单
            $detail = $detailModel->getOne(['detail_id' => $detailId],'product_name,quantity');
            $data['detail'][0]['product_name'] = $detail['product_name'];
            $data['detail'][0]['quantity'] = $detail['quantity'];
        }

//        var_dump($data);die;
        $this->assign('data',$data);
        return $this->fetch('orderslist/device/print');
    }
}
